import 'zx/globals';

const paths = {
  outdir: path.join(__dirname, '../dist'),
  srcdir: path.join(__dirname, '../src'),
  pkg: path.join(__dirname, '../package.json'),
};

const pkg = fs.readJsonSync(paths.pkg);

const externals = {
  emotion_css: `https://cdn.jsdelivr.net/npm/@emotion/css@11.1.3/dist/emotion-css.umd.min.js`,
  jquery: 'https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js',
  jquery_toast_plugin:
    'https://cdn.bootcdn.net/ajax/libs/jquery-toast-plugin/1.3.2/jquery.toast.min.js',
  jquery_toast_plugin_css:
    'https://cdn.bootcdn.net/ajax/libs/jquery-toast-plugin/1.3.2/jquery.toast.min.css',
  lodash: 'https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.min.js',
};
export const externalGlobalPluginConfig = {
  '@emotion/css': 'globalThis.emotion',
  jquery: 'globalThis.jQuery',
  lodash: 'globalThis._',
};

const buildConfig = [
  {
    name: 'tailwind-css',
    description: 'tailwind-css 辅助工具',
    include: ['https://tailwindcss.com/*'],
    require: [externals.jquery, externals.lodash, externals.jquery_toast_plugin],
    enableToast: true,
  },
  {
    name: 'hy-yapi-ts',
    description: 'hycode yapi to ts',
    include: ['https://api.succtime.com/project/*/interface/api/*'],
    require: [externals.jquery, externals.lodash, externals.jquery_toast_plugin],
    enableToast: true,
  },
].map((item) => {
  // @ts-ignore
  const { enableToast, resource = [], grant = [], ...other } = item;
  if (enableToast) {
    resource.push(`jquery_toast_plugin_css ${externals.jquery_toast_plugin_css}`);
    grant.push(`GM_getResourceText`, `GM_addStyle`);
  }
  const downloadURL = `https://gitee.com/liaoyinglong/tampermonkey-scripts/raw/main/dist/${item.name}/index.user.js`;
  return {
    ...other,
    grant,
    resource,
    'run-at': 'document-end',
    downloadURL,
    updateURL: downloadURL,
    author: pkg.author,
    version: pkg.version,
  };
});

function fromRoot(p: string) {
  return path.join(__dirname, '..', p);
}

const configs = buildConfig.map((item) => {
  let entry = fromRoot(`src/${item.name}/index.user.ts`);
  if (!fs.pathExistsSync(entry)) {
    entry = fromRoot(`src/${item.name}/index.user.js`);
  }
  return {
    userScriptConfig: item,
    entry,
    output: fromRoot(`dist/${item.name}/index.user.js`),
    devOutput: fromRoot(`dist/${item.name}/dev.user.js`),
  };
});

const isDev = process.env.BUILD_ENV === 'DEV';

export { paths, isDev, configs };
